//	Problem 060: XOR decryption

package main

import (
	"fmt"
	"projecteuler/euler"
	"strconv"
)

func check060(p1, p2 int) bool {
	if p1 != 3 && p2 != 3 {
		if p1%3 != p2%3 {
			return false
		}
	}
	p1p2, _ := strconv.Atoi(strconv.Itoa(p1) + strconv.Itoa(p2))
	if euler.IsPrime(p1p2) {
		p2p1, _ := strconv.Atoi(strconv.Itoa(p2) + strconv.Itoa(p1))
		if euler.IsPrime(p2p1) {
			return true
		}
	}
	return false
}

func p060() {
	euler.FillPrime(20000)
	sum := 100000
	for ai, a := range euler.PrimeList[1:] {
		for bi, b := range euler.PrimeList[ai+1:] {
			if (a + 4*b + 16) > sum {
				break
			}
			if !check060(a, b) {
				continue
			}
			for ci, c := range euler.PrimeList[ai+bi+1:] {
				if (a + b + 3*c + 8) > sum {
					break
				}
				if !check060(a, c) || !check060(b, c) {
					continue
				}
				for di, d := range euler.PrimeList[ai+bi+ci+1:] {
					if (a + b + c + 2*d + 2) > sum {
						break
					}
					if !check060(a, d) || !check060(b, d) || !check060(c, d) {
						continue
					}
					for _, e := range euler.PrimeList[ai+bi+ci+di+1:] {
						if (a + b + c + d + e) > sum {
							break
						}
						if !check060(a, e) || !check060(b, e) || !check060(c, e) || !check060(d, e) {
							continue
						} else {
							if x := a + b + c + d + e; x < sum {
								sum = x
								//fmt.Println(a, b, c, d, e, (a + b + c + d + e))
								break
							}
						}

					}
				}
			}
		}
	}

	fmt.Println("Problem 060：", sum)
}
